package com.example.aircraftticketingsystemserver.controller;

import com.example.aircraftticketingsystemserver.entity.Menu;
import com.example.aircraftticketingsystemserver.entity.User;
import com.example.aircraftticketingsystemserver.entity.UserRole;
import com.example.aircraftticketingsystemserver.mapper.UserRoleMapper;
import com.example.aircraftticketingsystemserver.service.IMenuService;
import com.example.aircraftticketingsystemserver.service.IUsersService;
import com.example.aircraftticketingsystemserver.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lxz
 * @since 2024-08-05
 */
@RestController
@CrossOrigin(origins = {"*","null"})
@RequestMapping("/user")
public class UsersController {
    @Resource
    private IUsersService usersService;
    @Resource
    private IMenuService menuService;
    @Resource
    UserRoleMapper userRoleMapper;
    /**
     * 通过token获取用户信息
     */
    @GetMapping("/getUserByToken")
    public Result getUserByToken(String token){
        User user = usersService.getUserByToken(token);
        List<Menu> menus=menuService.getMenuTree();
        Map<String,Object> map=new HashMap<>();
        map.put("user",user);
        map.put("menus",menus);
        return Result.ok(map);
    }
    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user)
    {
        User login=usersService.login(user);
        if(Objects.nonNull(login)){
            return Result.ok(login);}
        else return Result.error("用户名或密码错误");
    }
    /**
     * 注册用户
     */
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        user.setToken(System.currentTimeMillis()+"");
        if (user.getAvatar() == null || user.getAvatar().trim().isEmpty()) {
            user.setAvatar("https://img0.baidu.com/it/u=3366443890,3137275928&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1723222800&t=e9c77dbeae29048d534714403d5936bd");
        }
        User user1=usersService.addUser(user);
        UserRole userRole=new UserRole();
        userRole.setUserId(user1.getUserId());
        userRole.setRoleId(2);
        userRoleMapper.insert(userRole);
        return Result.ok();
    }

}
